import { getPhoneNumberInfo } from './getPhoneNumberInfo';
import { getOpenUserInfo } from './getOpenUserInfo';

const USER_INFO_STRATEGIES = {
    phone: getPhoneNumberInfo,
    openUserInfo: getOpenUserInfo,
    none: () => Promise.resolve(null),
};

/**
 * 获取支付宝授权码并可选获取用户信息
 * @param {string} userInfoType - 'phone' | 'openUserInfo' | 'none'
 * @returns {Promise<{authCode: string, userInfo?: object}>}
 */
export function getAlipayAuthCode(userInfoType = 'none') {
    return new Promise((resolve, reject) => {
        const strategy = USER_INFO_STRATEGIES[userInfoType];

        if (!strategy) {
            return reject(new Error(`不支持的 userInfoType: ${userInfoType}`));
        }

        my.getAuthCode({
            scopes: ['auth_base'],
            success: async (res) => {
                try {
                    const userInfo = await strategy();
                    resolve({ authCode: res.authCode, userInfo });
                } catch (e) {
                    reject(e);
                }
            },
            fail: () => {
                uni.showModal({
                    title: "提示",
                    content: "取消授权可能导致服务无法使用或页面显示不完整",
                    success: function(res) {
                        if (res.confirm) {
                            reject(new Error('用户取消授权'));
                        } else {
                            reject(new Error('用户点击重新授权'));
                        }
                    }
                });
            }
        });
    });
}